package com.leyou.order.controller;

import com.leyou.order.dto.OrderDTO;
import com.leyou.order.dto.OrderVO;
import com.leyou.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    //清理超时未支付订单
    @GetMapping("/clean")
    public ResponseEntity<Map<Long, Integer>> clean() {
        Map<Long, Integer> map = orderService.clean();
        return ResponseEntity.ok(map);
    }

    @GetMapping("/echo")
    public ResponseEntity<String> echo(HttpServletRequest request) {
        int remotePort = request.getRemotePort();//取得客户端的端口
        int localPort = request.getLocalPort();//取得服务器端口
        int a = remotePort + localPort;
        return ResponseEntity.ok(String.valueOf(a));
    }

    /**
     * 下单
     */
    @PostMapping("/order")
    public ResponseEntity<Long> saveOrder(@RequestBody OrderDTO orderDTO) {
        Long orderId = orderService.saveOrder(orderDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(orderId);
    }

    /**
     * 查询订单
     */
    @GetMapping("/order/{id}")
    public ResponseEntity<OrderVO> findOrderVOById(@PathVariable("id") Long id) {
        OrderVO orderVO = orderService.findOrderVOById(id);
        return ResponseEntity.ok(orderVO);
    }

    /**
     * 获取支付链接
     */
    @GetMapping("/order/url/{id}")
    public ResponseEntity<String> getPayUrl(@PathVariable("id") Long id) {
        String payUrl = orderService.getPayUrl(id);
        return ResponseEntity.ok(payUrl);
    }

    /**
     * 查询支付状态
     */
    @GetMapping("/order/state/{id}")
    public ResponseEntity<Integer> queryOrderStatus(@PathVariable("id") Long id) {
        Integer orderStatus = orderService.queryOrderStatus(id);
        return ResponseEntity.ok(orderStatus);
    }

    /**
     * 我的订单订单分页显示
     */
    @GetMapping("/order/list")
    public ResponseEntity<PageResult<OrderVO>> orderPageList(
            @RequestParam(value = "status",required = false) Integer status,
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rows",defaultValue = "5") Integer rows) {
        PageResult<OrderVO> orders = orderService.orderPageList(status,page, rows);
        return ResponseEntity.ok(orders);
    }

}